<?php
namespace App\Repositories;

use App\Models\User;
use App\Models\WechatUser;

class UserRepository
{
    /**
     * @param $openid
     * @return User
     */
    public function attemptWechatLogin($openid)
    {
        $wechatUser = $this->findWechatUserByOpenid($openid);
        if (is_null($wechatUser)) {
            $user = $this->refreshToken(new User);
            $wechatUser = new WechatUser;
            $wechatUser->openid = $openid;
            $wechatUser->user()->associate($user);
            $wechatUser->save();
        } else {
            $this->refreshToken($wechatUser->user);
        }
        return $wechatUser->user;
    }

    /**
     * @param User $user
     * @return User
     */
    public function refreshToken(User $user)
    {
        $user->api_token = str_random(60);
        $user->save();
        return $user;
    }

    /**
     * @param $openid
     * @return WechatUser|null
     */
    public function findWechatUserByOpenid($openid)
    {
        return WechatUser::where('openid', $openid)->first();
    }
}